﻿using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

using Microsoft.AspNetCore.Http;

namespace AhCha.Fortunate.Common.Utility
{
    public class HttpManager
    {

        /// <summary>
        /// 普通发送Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="contentType"></param>
        /// <param name="timeOut"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static Task<string> HttpPostAsync(string url, string postData = null, string contentType = null, Dictionary<string, string> headers = null)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            if (!string.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;
            }
            if (headers != null)
            {
                foreach (var header in headers)
                    request.Headers[header.Key] = header.Value;
            }

            try
            {
                byte[] bytes = Encoding.UTF8.GetBytes(postData ?? "");
                using (Stream sendStream = request.GetRequestStream())
                {
                    sendStream.Write(bytes, 0, bytes.Length);
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                    return streamReader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                return Task.FromResult(ex.Message);
            }

        }

        /// <summary>
        /// 普通发送Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static Task<string> HttpGetAsync(string url, Dictionary<string, string>? headers = null)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                if (headers != null)
                {
                    foreach (var header in headers)
                        request.Headers[header.Key] = header.Value;
                }
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    Stream responseStream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(responseStream);
                    return streamReader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                return Task.FromResult(ex.Message);
            }
        }

        /// <summary>
        /// 普通发送Get请求GBK
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetGbkAsync(string url)
        {
            using (HttpClient client = new HttpClient())
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();
                byte[] responseBytes = await response.Content.ReadAsByteArrayAsync();
                string responseBody = Encoding.GetEncoding("GBK").GetString(responseBytes);
                return responseBody;
            }
        }

        /// <summary>
        /// 普通发送Get请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpClientGetAsync(string url, Dictionary<string, string>? headers = null)
        {
            using HttpClient client = new HttpClient();
            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    if (headers != null)
                    {
                        foreach (var header in headers)
                        {
                            request.Headers.Add(header.Key, header.Value);
                        }
                    }
                    using (var response = await client.SendAsync(request))
                    {
                        var responseBody = await response.Content.ReadAsStringAsync();
                        return responseBody;
                    }
                }
            }
            catch (Exception)
            {
                return string.Empty;
            }

        }

        /// <summary>
        /// Post（application/x-www-form-urlencoded）
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="formData"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpClientPostFormAsync(string Url, List<KeyValuePair<string, string>> formData, Dictionary<string, string>? headers = null)
        {
            /*
             // 构建 formData 列表
        List<KeyValuePair<string, string>> formData = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("field1", "value1"),
            new KeyValuePair<string, string>("field2", "value2"),
            // 添加更多字段和值
        };
             */
            using HttpClient client = new HttpClient();
            try
            {
                var content = new FormUrlEncodedContent(formData);
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }

                HttpResponseMessage response = await client.PostAsync(Url, content);
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException e)
            {
                return e.Message;
            }
        }
       
        public static async Task<string> HttpClientPostFormAsync(string Url, Dictionary<string, string> formData, Dictionary<string, string>? headers = null)
        {
            using HttpClient client = new HttpClient();
            try
            {
                var content = new FormUrlEncodedContent(formData);
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                    }
                }

                HttpResponseMessage response = await client.PostAsync(Url, content);
                return await response.Content.ReadAsStringAsync();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

        /// <summary>
        /// Post （application/json）
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="ParamData"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static async Task<string> HttpClientPostJson(string Url, string ParamData, Dictionary<string, string>? headers = null)
        {
            try
            {
                using HttpClient client = new HttpClient();
                var content = new StringContent(ParamData, Encoding.UTF8, "application/json");
                if (headers != null)
                {
                    foreach (var header in headers)
                        client.DefaultRequestHeaders.Add(header.Key, header.Value);
                }
                HttpResponseMessage response = await client.PostAsync(Url, content);
                string responseBody = await response.Content.ReadAsStringAsync();
                return responseBody;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// Post（multipart/form-data; ）
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="file">文件</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async Task<string> HttpClientPostFormData(string url, IFormFile file)
        {
            using HttpClient client = new HttpClient();
            try
            {
                var formData = new MultipartFormDataContent();

                var streamContent = new StreamContent(file.OpenReadStream());
                streamContent.Headers.ContentType = new MediaTypeHeaderValue(file.ContentType);
                formData.Add(streamContent, "file", file.FileName);

                var response = await client.PostAsync(url, formData);
                if (!response.IsSuccessStatusCode)
                {
                    throw Oops.Oh("上传失败");
                }
                return await response.Content.ReadAsStringAsync();
            }
            catch (HttpRequestException ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// form-data;
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static async Task<string> HttpClientPostFormAsync(string Url, Dictionary<string, string> parameters)
        {
            using (var httpClient = new HttpClient())
            {
                // 创建一个 MultipartFormDataContent 对象
                var formData = new MultipartFormDataContent();
                foreach (var param in parameters)
                {
                    formData.Add(new StringContent(param.Value), param.Key);
                }

                var response = await httpClient.PostAsync(Url, formData);
                response.EnsureSuccessStatusCode();
                // 读取响应内容
                return await response.Content.ReadAsStringAsync();
            }
        }

        /// <summary>
        /// form-data;
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="formData"></param>
        /// <returns></returns>
        public static string HttpClientPostForm(string Url, Dictionary<string, string> formData)
        {
            using (var httpClient = new HttpClient())
            {
                using (var content = new MultipartFormDataContent())
                {
                    foreach (var field in formData)
                    {
                        content.Add(new StringContent(field.Value), field.Key);
                    }
                    HttpResponseMessage response = httpClient.PostAsync(Url, content).Result;
                    response.EnsureSuccessStatusCode();
                    return response.Content.ReadAsStringAsync().Result;
                }
            }
        }
        
        public static async Task<string> HttpClientSaveImg(string Url)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 发送请求以异步下载图片
                    HttpResponseMessage response = await client.GetAsync(Url);

                    // 确保请求成功
                    response.EnsureSuccessStatusCode();

                    // 读取返回的字节流
                    byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();

                    // 确保目标目录存在
                    if (!Directory.Exists(FileUtil.GetSystemDirectory))
                    {
                        Directory.CreateDirectory(FileUtil.GetSystemDirectory);
                    }
                    // 将字节流写入本地文件
                    await File.WriteAllBytesAsync(FileUtil.GetSystemDirectory + "/" + FileUtil.GetFileName(Url), imageBytes);
                    return Path.Combine(FileUtil.GetSystemDirectory, FileUtil.GetFileName(Url));
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <returns></returns>
        public static async Task<string> ImageUrlToBase64Async(string imageUrl)
        {
            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    byte[] imageBytes = await httpClient.GetByteArrayAsync(imageUrl);
                    string base64String = Convert.ToBase64String(imageBytes);
                    return base64String;
                }
                catch (Exception ex)
                {
                    return "";
                }
            }
        }
        
        public static string ImageUrlToBase64(string imageUrl)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(imageUrl);
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (BinaryReader binaryReader = new BinaryReader(responseStream))
                        {
                            byte[] imageBytes = binaryReader.ReadBytes((int)responseStream.Length);
                            return Convert.ToBase64String(imageBytes);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 传base64 图片文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="formData"></param>
        /// <param name="headers"></param>
        /// <returns></returns>
        public static string HttpWebRequestPostFormData(string url, Dictionary<string, string> formData, Dictionary<string, string> headers = null)
        {
            try
            {
                // 创建边界字符串
                string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "POST";
                request.ContentType = "multipart/form-data; boundary=" + boundary;

                // 构建 multipart/form-data 请求体
                using (MemoryStream requestStream = new MemoryStream())
                {
                    // 添加所有表单字段（包括 Base64 图片字段）
                    if (formData != null)
                    {
                        foreach (var pair in formData)
                        {
                            // 每个字段的格式
                            string fieldTemplate =
                                $"--{boundary}\r\n" +
                                $"Content-Disposition: form-data; name=\"{pair.Key}\"\r\n\r\n" +
                                $"{pair.Value}\r\n";

                            byte[] fieldBytes = Encoding.UTF8.GetBytes(fieldTemplate);
                            requestStream.Write(fieldBytes, 0, fieldBytes.Length);
                        }
                    }

                    // 添加结束边界
                    string endBoundary = $"--{boundary}--\r\n";
                    byte[] endBoundaryBytes = Encoding.UTF8.GetBytes(endBoundary);
                    requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);

                    // 写入请求流
                    request.ContentLength = requestStream.Length;
                    requestStream.Seek(0, SeekOrigin.Begin);
                    using (Stream networkStream = request.GetRequestStream())
                    {
                        requestStream.CopyTo(networkStream);
                    }
                }

                // 添加自定义头信息
                if (headers != null)
                {
                    foreach (var header in headers)
                    {
                        if (header.Key.Equals("Content-Type", StringComparison.OrdinalIgnoreCase))
                            continue;

                        request.Headers.Add(header.Key, header.Value);
                    }
                }

                // 获取响应
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream responseStream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(responseStream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                // 实际项目中建议记录日志
                return string.Empty;
            }
        }

        public static string PostWebRequestJson(string postUrl, string paramData, Encoding dataEncode)
        {
            string ret = string.Empty;
            try
            {
                byte[] byteArray = dataEncode.GetBytes(paramData); //转化

                ServicePointManager.SecurityProtocol = (SecurityProtocolType)192 | (SecurityProtocolType)768 | (SecurityProtocolType)3072;
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));

                webReq.Method = "POST";
                webReq.ContentType = "application/json";
                webReq.Accept = "application/json";
                webReq.Timeout = 30000;
                webReq.ContentLength = byteArray.Length;
                Stream newStream = webReq.GetRequestStream();
                newStream.Write(byteArray, 0, byteArray.Length);//写入参数
                newStream.Close();

                HttpWebResponse response = (HttpWebResponse)webReq.GetResponse();
                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                ret = sr.ReadToEnd();
                sr.Close();
                response.Close();
                newStream.Close();
            }
            catch (Exception ex)
            {

            }
            return ret;
        }


    }
}